package org.smartercontext.local.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.smartercontext.contextmger.contextsphere.ContextSphereController;
import org.smartercontext.contextmger.contextsphere.Permissions;

/**
 * Servlet implementation class ManagePermissionsServlet
 */
@WebServlet("/ManagePermissionsServlet")
public class ManagePermissionsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ManagePermissionsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
    	HttpSession session = request.getSession();
    	if(session.getAttribute("username")!=null){
    		String username = session.getAttribute("username").toString();

    		ContextSphereController csc = new ContextSphereController();
    		   		
    		String values[] = request.getParameterValues("perm");
    		
    		if(values!=null){
    		
    		List<Permissions>userPerms = new ArrayList<>();
    		
    		for(int i=0;i<values.length;i++){
    			String idStr = values[i];
    			Integer idPerm = Integer.valueOf(idStr);
    			Permissions searched = csc.getPermission(idPerm);
    			userPerms.add(searched);
    		}
    		
    		csc.setListUserPermissions(userPerms, username);
    		
    		}else{
    			csc.setListUserPermissions(null, username);
    		}
    		response.sendRedirect("userPermissions.jsp");
    	}
    	
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
